import mongoose from 'mongoose';
import log4js from 'koa-log4';
import _ from 'lodash';
import pmx from 'pmx';
import waitHandler from '../handler/waitHandler';
import componentContainer from '../../components/componentContainer';

const logger = log4js.getLogger('WeChatWaitListThreshold');
const probe = pmx.probe();

// The counter will start at 0
const counter = probe.counter({
  name: 'WeChat Threshold Hint',
});

class WeChatWait {
  async getSystemRobot() {
    if (this.systemRobot) return this.systemRobot;

    const User = mongoose.model('User');
    const systemRobot = User.getSystemRobot();
    this.systemRobot = systemRobot;
    return systemRobot;
  }

  async sendMessage(messageHandler, toChannel, message) {
    const systemRobot = await this.getSystemRobot();
    await messageHandler.post(toChannel, systemRobot, message);
  }

  async handle({ user, message, messageHandler }) {
    if (!WeChatWait.isMessageFromStudent(user)) return;

    const isOverload = await this.isOverload(user.group.id);
    if (!isOverload) return;

    const isInService = await this.isInService(user, message.toChannel);
    if (isInService) return;

    counter.inc();
    await this.sendMessage(messageHandler, message.toChannel, {
      mention: [user.id],
      toSocialId: message.fromSocialId,
      subType: 'text',
      body: `@${user.nickname}: 非常抱歉，当前咨询量较大，请稍作等候，我们将尽快回复您。`,
    });
  }

  async isInService(user, channelId) {
    const Channel = mongoose.model('Channel');
    const channel = await Channel.findById(channelId);

    if (!channel) {
      logger.error('Channel not found for %s, channelId %s', user.id, channelId);
      return true;
    }

    return channel.isInService(user);
  }

  async isOverload(groupId) {
    const redis = componentContainer.getRedis();
    const thresholdRaw = await redis.get('student:waitList:threshold');
    const threshold = _.isNumber(Number(thresholdRaw)) ? Number(thresholdRaw) : 0;

    if (threshold === 0) return false;

    const studentWaitCountRaw = await waitHandler.countByGroupId(groupId);
    const studentWaitCount = _.isNumber(Number(studentWaitCountRaw))
      ? Number(studentWaitCountRaw)
      : 0;

    return studentWaitCount > threshold;
  }

  static isMessageFromStudent(user) {
    return user.group.name === '学生';
  }
}

const offDutyReply = new WeChatWait();

export default offDutyReply;
